package cn.jiangjiesheng.bootstrap.commons.utils;

import cn.jiangjiesheng.bootstrap.commons.entity.Image;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by dev@jiangjiesheng.cn on 2020/1/3.
 */
@Slf4j
public class ImageUtil {

    public static boolean isImage(File file) throws IOException {
        return ImageIO.read(file) != null;
    }

    /**
     * 获取图片类型
     * .jpg .jpeg .jpe .jfif ===> JPEG
     * .png ===> png
     * .gif ===> gif
     */
    public static String getImageType(File file) {

        try {
            @Cleanup ImageInputStream inputStream = ImageIO.createImageInputStream(file);
            Iterator<ImageReader> iter = ImageIO.getImageReaders(inputStream);
            ImageReader reader = iter.next();
            return reader.getFormatName();
        } catch (Exception ex) {
            log.error("getImageType-error:", ex);
        }

        return null;
    }

    public static Image parseImage(File file) {
        try {
            if (!isImage(file)) return null;

            Image result = new Image();
            result.setFileExtension(getImageType(file));

            BufferedImage bufferedImage = ImageIO.read(file);
            result.setWidth(bufferedImage.getWidth());
            result.setHeight(bufferedImage.getHeight());

            result.setFileSize(file.length());

            return result;
        } catch (Exception ex) {
            log.error("parseImage errro:", ex);
        }
        return null;
    }


}
